package com.hwua.daoimpl;

import com.hwua.dao.IDvdDao;
import com.hwua.domain.Dvd;
import com.hwua.util.ConnectionTools;

import javax.xml.transform.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DvdDaoImpl implements IDvdDao {
    private Connection connection;


    @Override
    public boolean addDvd(Dvd dvd) throws SQLException {
        //--1.获取数据库连接
        connection = ConnectionTools.getConnection();
        //--2.提供执行的sql语句 ？是占位符
        String sql = "insert into dvd(dvd_id,dvd_name) values(?,?)";
        //--通过连接预处理类
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //--4.给占位符赋值
        preparedStatement.setInt(1,dvd.getDvdId());
        preparedStatement.setString(2,dvd.getDvdName());

        int result = preparedStatement.executeUpdate();
        return result != 0;
    }

    @Override
    public List<Dvd> getAllDvd() throws SQLException {
        //--0.提供容器
        List<Dvd> list = new ArrayList<>(10);
        //--1.获取连接
        connection = ConnectionTools.getConnection();
        //--2.设置要执行的sql
        String sql="select dvd_id,dvd_name from dvd";
        //--3.利用连接获取perparedstatement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //--4.执行sql语句 查询有专用的方法
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            int dvd_id = resultSet.getInt("dvd_id");
            String dvd_name = resultSet.getString("dvd_name");
            Dvd d = new Dvd();
            d.setDvdId(dvd_id);
            d.setDvdName(dvd_name);
            list.add(d);
        }
        return list;
    }
}
